;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Barcode.PackageCode", [])
        .controller("PackageCodeCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "EventBus", "MESG_TYPE", "$filter", "UserContextService", "$timeout", function ($scope, $state, ybWidget, ybHttp, EventBus, MESG_TYPE, $filter, UserContextService, $timeout) {
            var lodop;
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.markInfo = {
                allCheckedBill: false,
                allCheckedMaterial: false,
                curRow: -1
            };
            $scope.condition = {};
            $scope.toolbarConfig = {
                showPrintConf: false
            };
            $scope.dataList = [];
            $scope.detailInfo = {};
            $scope.packList = [];
            $scope.currentMaterial = {};
            $scope.markInfo = {};
            $scope.printTypeObj = {
                type: "0"
            };
            $scope.tempSet = {
                qrCodeSize: 85,
                printMainCode: true,
            };
            $scope.tableConfig = {
                scrollWidth: 720,
                tableCol: [
                    {
                        type: "",
                        name: "序号",
                        dataField: "seq",
                        width: 60
                    },
                    {
                        type: "",
                        name: "打印标志",
                        dataField: "stateName",
                        width: 90
                    },
                    {
                        type: "",
                        name: "零件编号",
                        dataField: "materialsNo",
                        width: 120
                    },
                    {
                        type: "",
                        name: "零件中文名",
                        dataField: "materialsDes",
                        width: 120
                    },
                    {
                        type: "",
                        name: "数量",
                        dataField: "qty",
                        width: 80
                    },
                    {
                        type: "",
                        name: "未打数量",
                        dataField: "restAmount",
                        width: 100
                    },
                    {
                        type: "",
                        name: "仓库",
                        dataField: "outLocation",
                        width: 80
                    },
                    /*{
                     type: "",
                     name: "所属公司",
                     dataField: "agentName",
                     width: 100
                     },*/
                    {
                        type: "",
                        name: "操作标志",
                        dataField: "statusName",
                        width: 90
                    }
                ]
            };

            $scope.details = [];

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            var btnPermissionCode = {
                packageCodePrint: window.ActionCode.packageCodePrint
            };

            $scope.btnPermission = {
                packageCodePrint: true
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            function getDataList() {
                var service = "device";
                var reqUrl = "/warehouseInbound/itemByOrder";
                var param = {
                    order: $scope.condition.billNo
                };

                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }

                    $scope.markInfo.curRow = null;
                    $scope.detailInfo = {};
                    $scope.packList = [];
                    $scope.printTypeObj.type = "0";


                    var billObj = resp.value;
                    if (!billObj) {
                        $scope.dataList = [];
                        return;
                    }
                    angular.forEach(billObj.detailList, function (item) {
                        item.isChecked = false;
                        item.stateName = $filter('printState')(item.printState);
                        item.statusName = $filter('allotState')(item.printState);
                        item.materialsDes = item.materialName;
                        item.materialsNo = item.materialNo;
                        item.qty = item.amount;
                        item.billNo = item.businessOrder;
                        item.outLocation = billObj.headerInfo.warehouseCode;
                        item.restAmount = item.amount - item.printNum;
                    });
                    $scope.dataList = billObj.detailList;
                    $scope.markInfo.allCheckedMaterial = false;
                });
            }

            $scope.printTypeChange = function() {
                $scope.packList = [];
                $scope.currentMaterial = {};
                $scope.detailInfo = {};
                $scope.dataList = [];
            };

            // 总数量发生变化时调用
            $scope.countPack = function () {
                if ($scope.detailInfo.totalQty > $scope.currentMaterial.restAmount) {
                    $scope.detailInfo.totalQty = $scope.currentMaterial.restAmount;
                }

                handleDefaultPackNumAndEachPack();
            };

            // 包装数量发生变化时调用
            $scope.setPackNum = function () {
                $scope.detailInfo.packNum = parseInt($scope.detailInfo.packNum);

                if (!$scope.detailInfo.totalQty) {
                    // 直投打印时，总数量没有默认值，必须保证用户输入后再做后续操作
                    return
                }
                setEachPack();
            };

            function setEachPack(eachNum) {
                $scope.packList = [];
                var eachPackNum = eachNum || Math.floor($scope.detailInfo.totalQty / $scope.detailInfo.packNum);
                for (var i = 0; i < $scope.detailInfo.packNum; i++) {
                    var objData = {
                        currentQty: eachPackNum
                    };
                    if (i == $scope.detailInfo.packNum - 1) {
                        if (eachNum) {
                            objData.currentQty = $scope.detailInfo.totalQty % eachNum || eachNum;
                        } else {
                            objData.currentQty = Number((objData.currentQty + $scope.detailInfo.totalQty % $scope.detailInfo.packNum).toFixed(3));
                        }
                        $scope.packList.push(objData);
                    } else {
                        $scope.packList.push(objData);
                    }
                }
            }

            $scope.selectRow = function (index,item) {
                if ($scope.dataList[index].printState == 2) {
                    ybWidget.ShowToaster('error', '请选择未完成的零件打印');
                    return;
                }
                $scope.markInfo.curRow = index;
                $scope.currentMaterial = $scope.dataList[index];
                $scope.detailInfo.totalQty = $scope.currentMaterial.restAmount;
                handleDefaultPackNumAndEachPack();
            };

            function handleDefaultPackNumAndEachPack() {
                const defaultEachPack = getDefaultCurrentQty();
                if (defaultEachPack) {
                    $scope.detailInfo.packNum = Math.ceil($scope.detailInfo.totalQty / defaultEachPack) || '';
                }
                setEachPack(defaultEachPack);
            }

            function getDefaultCurrentQty() {
                if (!$scope.currentMaterial.restAmount) {
                    return $scope.currentMaterial.minPackingQty
                }

                if ($scope.currentMaterial.minPackingQty) {
                    return Math.min($scope.currentMaterial.minPackingQty, $scope.currentMaterial.restAmount)
                }

                return $scope.currentMaterial.restAmount
            }

            $scope.materialsNoBlur = function(value) {
                if (!value) return

                const param = {
                    filters: { materialsNos: value }
                }
                ybHttp.Post('device', '/materials/list', param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    const obj = resp.value.list[0] || {}
                    $scope.currentMaterial.minPackingQty = obj.minPackingQty
                    if ($scope.detailInfo.totalQty) {
                        handleDefaultPackNumAndEachPack();
                    }
                })
            };

            $scope.previewOrPrintTicket = function (type) {
                if ($scope.packList.length == 0) {
                    ybWidget.ShowMessage('没有可打印的条码');
                    return;
                }
                var amount = 0;
                angular.forEach($scope.packList, function (item) {
                    amount = Number((amount + parseFloat(item.currentQty)).toFixed(3));
                    item.barcodeDesc = $scope.detailInfo.barcodeDesc;
                    item.model = $scope.detailInfo.model;
                    item.orawyd = $scope.detailInfo.orawyd;
                });
                if (amount > $scope.detailInfo.totalQty) {
                    ybWidget.ShowMessage('每个包数量总和不得超过最大数量');
                    return;
                }
                var param = {
                    billNo: $scope.currentMaterial.billNo,
                    materialsNo: $scope.currentMaterial.materialsNo,
                    materialsDes: $scope.currentMaterial.materialsDes,
                    totalQty: amount,
                    totalSize: $scope.detailInfo.totalSize,
                    detailList: $scope.packList,
                    rowNo: $scope.currentMaterial.rowNo
                };
                var url = "/barcode/singlePrint";
                if ($scope.printTypeObj.type == 1) {
                    url = "/barcode/singleDirectPrint";
                    console.log($scope.detailInfo)
                    if (!$scope.detailInfo.materialsNo) {
                        ybWidget.ShowMessage('零件号必填');
                        return false;
                    }
                    param.materialsNo = $scope.detailInfo.materialsNo;
                    param.factorySapCode = $scope.detailInfo.factorySapCode;
                }
                ybHttp.Post('device', url, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    startPrint(type, resp.value, false);
                });
            };

            $scope.batchPreviewOrPrintForSelect = function (type) {
                if ($scope.details.length === 0) {
                    ybWidget.ShowMessage('请选择需要打印的零件');
                    return;
                }
                var service = "device";
                var reqUrl = "/barcode/batchPrintForSelect";
                var reqParam = [];
                angular.forEach($scope.details, function (item) {
                    if (item.amount > item.printNum) {
                        var obj = {};
                        obj.materialsNo = item.materialNo;
                        obj.materialsDes = item.materialName;
                        obj.totalQty = item.amount - item.printNum;
                        obj.billNo = $scope.condition.billNo;
                        obj.rowNo = item.rowNo;
                        reqParam.push(obj);
                    }
                    item.isChecked = false;
                });
                if (reqParam.length === 0) {
                    ybWidget.ShowMessage('没有可打印的零件');
                    return;
                }
                ybHttp.Post(service, reqUrl, reqParam).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp);
                        return;
                    }
                    startPrint(type, resp.value, true);
                });
            };

            $scope.printList = [];
            async function startPrint(type, printListArr, isBatch) {
                if (!$scope.tempSet.printMainCode) {
                    for (var i = 0; i < printListArr.length; i++) {
                        if (printListArr[i].barcodeFlag === 0) {
                            printListArr.splice(i, 1);

                            if (!isBatch) { // 非批量打印，只有一个总条码，找到 即 退出for循环
                                break;
                            }
                        }
                    }
                }

                var printType = $scope.tempSet.printType;

                $scope.printList = type === "preview" && printType !== 1 ? printListArr : UserContextService.ListGroup(printListArr, 20);

                lodop = UserContextService.GetLodop();
                if (!lodop) {
                    return;
                }

                if (!await UserContextService.InitPrinter(lodop, true, printType)) {
                    return;
                }

                setTimeout(function () {
                    UserContextService.ListPrint($scope.printList, lodop, printType, type === "preview");

                    getDataList();
                    $scope.printList = [];
                }, 300)
            }

            $scope.search = function () {
                getDataList();
            };

            $scope.exportParam = {};
            $scope.exportParam.outPutParam = {};
            $scope.exportParam.outPutUrl = ybHttp.RequestUrl("device", "/barcode/directPrintExportBatch");
            
            $scope.outPut = function () {
                if ($scope.packList.length == 0) {
                    ybWidget.ShowMessage('没有可打印的条码');
                    return false;
                }
                if (!$scope.detailInfo.materialsNo) {
                    ybWidget.ShowMessage('零件号必填');
                    return false;
                }
                var amount = 0;
                angular.forEach($scope.packList, function (item) {
                    amount = Number((amount + parseFloat(item.currentQty)).toFixed(3));
                    item.barcodeDesc = $scope.detailInfo.barcodeDesc;
                    item.model = $scope.detailInfo.model;
                    item.orawyd = $scope.detailInfo.orawyd;
                });
                if (amount > $scope.detailInfo.totalQty) {
                    ybWidget.ShowMessage('每个包数量总和不得超过最大数量');
                    return false;
                }
                var param = {
                    materialsNo: $scope.detailInfo.materialsNo,
                    totalQty: amount,
                    totalSize: $scope.detailInfo.totalSize,
                    detailListStr: JSON.stringify($scope.packList)
                };
                $scope.exportParam.outPutParam = param;
                return true;
            };

            function getBillIds() {
                $scope.details = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.details.push(item);
                    }
                });
            }

            $scope.selectSingle = function (item, list, type) {
                if (type == 'Material') {
                     setEachPack()
                }
                if (!item.isChecked) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    if (!checkAll(list)) {
                        $scope.markInfo["allChecked" + type] = false;
                    } else {
                        $scope.markInfo["allChecked" + type] = true;
                    }
                }
                getBillIds();
            };

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectAll = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });
                getBillIds();
            };

            (function () {
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }]);
})(window, window.angular);